/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package webOffline;

/**
 *
 * @author Do Viet Trung
 */
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.io.File;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

public class ProjectWizard implements ActionListener,
                                      ItemListener,
                                      MouseMotionListener,
                                      TableModelListener
{

    private static boolean RIGHT_TO_LEFT = false;
    private static String defaultAddress = "http://www.example.com";
    private static String defaultUpLinks = "3";
    private static final String ALLOW = "Allow    ";
    private static final String DENY =  "            Deny";
    private static int stateChange = 0;
    private boolean resultDialog = false;
    private String address ;
    private String projectName;
    private int upLink;
    private JFrame frame;
    private JDialog dialog;
    private JButton backBtn,
                    finishBtn,
                    cancelBtn,
                    choseFileBtn,
                    saveChangeBtn,
                    upPatternBtn,
                    downPatternBtn,
                    resetBtn,
                    deletePatternBtn;
    private JTextField addressTxt,
                        levelTxt,
                        outputTxt,
                        projectNameTxt;
    private JTextArea addressAreTxt;
    private JTable patternTable,
                    extTable;
    //private JLabel    addressLabel;
    private DefaultTableModel patternTableModel,
                                extTableModel;
    private int step = 0;
    private JTabbedPane tabbedPane;
    private JComboBox permissionCombo,
                       patternCombo;
    private JCheckBox allowAllCheckbox,
                        denyAllCheckbox;
    private String[] perStrings = {ALLOW,DENY};
    private ProjectAddress projectAddress;
    private boolean isNewAddressCreation = true,
                    isNewPatternCreation = true;
    Object[][] data = {{"",  ""},{"",""},{"",""},{"",""},{"",""}
                            ,{"",""},{"",""},{"",""},{"",""},{"",""}
                            ,{"",""},{"",""},{"",""},{"",""},{"",""}
                            ,{"",""},{"",""},{"",""},{"",""},{"",""}
                            ,{"",""},{"",""},{"",""},{"",""},{"",""}
                            ,{"",""},{"",""},{"",""},{"",""},{"",""}
                            ,{"",""},{"",""},{"",""},{"",""},{"",""}
                            ,{"",""},{"",""},{"",""},{"",""},{"",""}
                            ,{"",""},{"",""},{"",""},{"",""},{"",""}
                            ,{"",""},{"",""},{"",""},{"",""},{"",""}};
     Object[][] data2 = {{"1","",""},{"2","",""},{"3","",""},{"4","",""},{"5","",""},
                        {"6","",""},{"7","",""},{"8","",""},{"9","",""},{"10","",""},
                        {"11","",""},{"12","",""},{"13","",""},{"14","",""},{"15","",""},
                        {"16","",""},{"17","",""},{"18","",""},{"19","",""},{"20","",""},
                        {"21","",""},{"22","",""},{"23","",""},{"24","",""},{"25","",""},
                        {"26","",""},{"27","",""},{"28","",""},{"29","",""},{"30","",""},
                        {"31","",""},{"32","",""},{"33","",""},{"34","",""},{"35","",""},
                        {"36","",""},{"37","",""},{"38","",""},{"39","",""},{"40","",""}};

    public boolean getResultDialog() {
        return resultDialog;
    }

    public ProjectAddress getProjectAddress() {
        return projectAddress;
    }

    private JPanel createCenterPane() {
        JPanel centerPane = new JPanel();
        tabbedPane = new JTabbedPane();
        JComponent panel1 = makeComponentFirstTab();
        tabbedPane.addTab("General", panel1);
        //tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
       
        JComponent panel2 = makeComponentSecondTab();
        tabbedPane.addTab("Pattern", panel2);
        //tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);

        JComponent panel3 = makeComponentThirdTab();
        tabbedPane.addTab("Extension", panel3);
        //tabbedPane.setMnemonicAt(1, KeyEvent.VK_3);

        JComponent panel4 = makeComponentFourthTab();
        tabbedPane.addTab("Result", panel4);
        //tabbedPane.setMnemonicAt(1, KeyEvent.VK_4);

        tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        tabbedPane.setPreferredSize(new Dimension(390, 280));
        tabbedPane.setEnabledAt(0, false);
        tabbedPane.setEnabledAt(1, false);
        tabbedPane.setEnabledAt(2, false);
        tabbedPane.setEnabledAt(3, false);
        centerPane.add(tabbedPane);

        return centerPane;
    }
    
    private JComponent makeComponentFirstTab() {
        JPanel pane = new JPanel(new BorderLayout());
        JPanel rowCenter = new JPanel(new GridLayout(3, 1));
        JPanel row11 = new JPanel(new FlowLayout(0));
        JPanel row12 = new JPanel(new FlowLayout(0));
        JPanel row13 = new JPanel(new FlowLayout(0));

        addressTxt = new JTextField(35);
        addressTxt.setText("www.example.com");

        levelTxt = new JTextField(5);
        levelTxt.setText("3");

        outputTxt = new JTextField(30);

        projectNameTxt = new JTextField(10);
        projectNameTxt.setText("example");

        choseFileBtn = new JButton("...");
        choseFileBtn.setActionCommand("choseFileBtn");
        choseFileBtn.addActionListener(this);
        ImageIcon icon = new ImageIcon(WebOffline.imagesPath + "newProjectBg.png");

        row11.add(new JLabel("Starting Address: "));
        row11.add(addressTxt);

        row12.add(new JLabel("Up to:"));
        row12.add(levelTxt);
        row12.add(new JLabel(" links from this starting point."));
        row12.add(new JLabel("With name:"));
        row12.add(projectNameTxt);

        row13.add(new JLabel("Save project to:"));
        row13.add(outputTxt);
        row13.add(choseFileBtn);

        rowCenter.add(row11);
        rowCenter.add(row12);
        rowCenter.add(row13);

        pane.add(new JLabel(icon),BorderLayout.PAGE_START);
        pane.add(rowCenter, BorderLayout.CENTER);

        return pane;
    }
     
    private JComponent makeComponentSecondTab() {
        JPanel pane = new JPanel(new BorderLayout());
        //pane.setPreferredSize(new Dimension(400, 260));
        String[] columnNames = {"Priority","Pattern",
                "Permission"};

        patternTableModel = new DefaultTableModel(data2, columnNames);
        patternTable = new JTable(patternTableModel){
        @Override
            public boolean isCellEditable(int row, int column) {
                if (column == 0) {
                    return false;
                }
                else {
                    return true;
                }
            }
        };

        JScrollPane treeScrollPane = new JScrollPane(patternTable);
        patternTable.setFillsViewportHeight(true);
        patternTable.setPreferredScrollableViewportSize(new Dimension(100, 100));
        patternTableModel.addTableModelListener(this);
        patternTable.setName("patternTable");
        //patternTable.setPreferredSize(new Dimension(300, 220));
        TableColumn permissionColumn = patternTable.getColumnModel().getColumn(2);
        permissionCombo = new JComboBox(perStrings);
        permissionColumn.setCellEditor(new DefaultCellEditor(permissionCombo));
        TableColumn column = null;

        for (int i = 0; i < 3; i++) {
            column = patternTable.getColumnModel().getColumn(i);
//            if(i != 2)
//                column.setResizable(true);
            if (i == 1) {
                column.setPreferredWidth(270); //third column is bigger
            }
//            if(i==2)
//            {
//                 column.setPreferredWidth(105);
//            }
//            else
//            {
//                column.setPreferredWidth(15);
//            }
        }
//        addressLabel = new JLabel(defaultAddress);
//        addressLabel.setFont(new Font("Tahoma", Font.BOLD , 10));
        addressAreTxt = new JTextArea();
        addressAreTxt.setPreferredSize(new Dimension(360, 25));
        addressAreTxt.setEditable(false);
        addressAreTxt.setWrapStyleWord(true);
        addressAreTxt.setLineWrap(true);
        addressAreTxt.setFont(new Font("Tahoma", Font.BOLD , 10));
        addressAreTxt.setAutoscrolls(true);
        addressAreTxt.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
        addressAreTxt.setToolTipText(addressAreTxt.getText());
        addressAreTxt.setName("addressAreaTxt");
        addressAreTxt.addMouseMotionListener(this);

        JScrollPane scrollAddressArea = new JScrollPane(addressAreTxt, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollAddressArea.setMinimumSize(new Dimension(360, 25));
        scrollAddressArea.setMaximumSize(new Dimension(360, 25));

        JPanel row1 = new JPanel(new FlowLayout(0));
        JPanel row2 = new JPanel(new FlowLayout(0));
        JPanel pageStart = new JPanel(new GridLayout(2, 1));

        ImageIcon icon1 = new ImageIcon(WebOffline.imagesPath + "upIcon.png");
        ImageIcon icon2 = new ImageIcon(WebOffline.imagesPath + "downIcon.png");
        ImageIcon icon3 = new ImageIcon(WebOffline.imagesPath + "deleteIcon.png");
        ImageIcon icon4 = new ImageIcon(WebOffline.imagesPath + "resetIcon.png");

        resetBtn = new JButton(icon4);
        resetBtn.setActionCommand("resetBtn");
        resetBtn.addActionListener(this);
        resetBtn.setToolTipText("Clear All Patterns");

        deletePatternBtn = new JButton(icon3);
        deletePatternBtn.setActionCommand("deletePatternBtn");
        deletePatternBtn.addActionListener(this);
        deletePatternBtn.setToolTipText("Delete Selected Pattern");

        upPatternBtn = new JButton(icon1);
        upPatternBtn.setActionCommand("upPatternBtn");
        upPatternBtn.addActionListener(this);
        upPatternBtn.setToolTipText("Up Priority");

        downPatternBtn = new JButton(icon2);
        downPatternBtn.setActionCommand("downPatternBtn");
        downPatternBtn.addActionListener(this);
        downPatternBtn.setToolTipText("Down Priority");

        row1.add(scrollAddressArea);
        row2.add(downPatternBtn);
        row2.add(upPatternBtn);
        row2.add(deletePatternBtn);
        row2.add(resetBtn);

        pageStart.add(row1);
        pageStart.add(row2);
        pageStart.setPreferredSize(new Dimension(400, 65));

        pane.add(pageStart, BorderLayout.PAGE_START);
        pane.add(treeScrollPane, BorderLayout.CENTER);
        pane.add(new JLabel("Example pattern: /default/*; /index/* or /default/*.jpg ; /index/*.jpg; ..."), BorderLayout.PAGE_END);

        patternTable.setRowHeight(20);

        return pane;
    }

    private JPanel makeComponentThirdTab() {
         JPanel pane = new JPanel(new BorderLayout());
         String[] columnNames = {"Extension",
                    "Permission"};
         ArrayList<String> arrExt = null;
         try {
            arrExt = DOMXml.readFileTypes(Option.FileTypePath);
         } catch(Exception ec) {
             JOptionPane.showMessageDialog(frame, ec.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
         }

         Object [][]extData = new Object[arrExt.size()][2];
         for(int i = 0; i < arrExt.size(); i++)
         {
             extData[i][0] = arrExt.get(i);
             extData[i][1] = "Allow";
         }
         extTableModel = new DefaultTableModel(extData, columnNames);

         extTable = new JTable(extTableModel){
            @Override
            public boolean isCellEditable(int row, int column) {
            if (column == 1) {
                return true;
            } else
                return false;
            }
         };
         
         JScrollPane treeScrollpane = new JScrollPane(extTable);
         extTable.setFillsViewportHeight(true);
         extTable.setPreferredScrollableViewportSize(new Dimension(100, 100));
         TableColumn permissionColumn = extTable.getColumnModel().getColumn(1);
         permissionCombo = new JComboBox(perStrings);
         permissionCombo.setSelectedIndex(0);
         permissionColumn.setCellEditor(new DefaultCellEditor(permissionCombo));
         TableColumn column = null;

         for (int i = 0; i < 2; i++) {
            column = extTable.getColumnModel().getColumn(i);
            if (i == 0) {
                column.setPreferredWidth(250); 
            }
            else {
                column.setPreferredWidth(15);

            }
         }

         JPanel pageStartPane = new JPanel(new GridLayout(3, 1));
         JPanel row1 = new JPanel(new FlowLayout(0));
         JPanel row2 = new JPanel(new FlowLayout(0));
         JPanel row3 = new JPanel(new FlowLayout(0));
         JPanel pageEnd = new JPanel(new FlowLayout(0));
         row1.add(new JLabel("Permission for all of extensions: "));

         allowAllCheckbox = new JCheckBox("Allow all");
         allowAllCheckbox.setName("allowAllCheckbox");
         allowAllCheckbox.addItemListener(this);

         denyAllCheckbox = new JCheckBox("Deny all");
         denyAllCheckbox.setName("denyAllCheckbox");
         denyAllCheckbox.addItemListener(this);

         ImageIcon icon = new ImageIcon(WebOffline.imagesPath + "/saveIcon.png");
         saveChangeBtn = new JButton(icon);
         saveChangeBtn.setToolTipText("Save configuration of this pattern");
         //saveChangeBtn.setEnabled(false);
         row1.add(allowAllCheckbox);
         row1.add(denyAllCheckbox);
         row3.add(new JLabel("OR redefine with below extensions:"));
         //row3.add(saveChangeBtn);
         saveChangeBtn.setActionCommand("saveChangeBtn");
         saveChangeBtn.addActionListener(this);

         patternCombo = new JComboBox(columnNames);
         patternCombo.setPreferredSize(new Dimension(250 , 25));

         row2.add(new JLabel("Patterns:"));
         row2.add(patternCombo);
         row2.add(saveChangeBtn);

         pageStartPane.add(row2);
         pageStartPane.add(row1);
         pageStartPane.add(row3);
         pageStartPane.setPreferredSize(new Dimension(120, 90));

         patternCombo.setActionCommand("patternCombo");
         patternCombo.addActionListener(this);
         //patternCombo.addItemListener(this);
         ImageIcon icon2 = new ImageIcon(WebOffline.imagesPath + "/warningIcon.png");
         pageEnd.add(new JLabel(icon2));
         pageEnd.add(new JLabel("These above configuration only affects PATTERN without /*."));
         //pageEnd.add(saveChangeBtn);
         pane.add(pageStartPane,BorderLayout.PAGE_START);
         pane.add(treeScrollpane, BorderLayout.CENTER);
         pane.add(pageEnd, BorderLayout.PAGE_END);

         return pane;
    }
     
    private JPanel makeComponentFourthTab() {
         JPanel pane = new JPanel(new BorderLayout());
         ImageIcon icon = new ImageIcon(WebOffline.imagesPath + "successfulBg.png");

         JLabel bg = new JLabel(icon);
         pane.add(bg, BorderLayout.PAGE_START);

         JLabel temp = new JLabel("   New Project Winzard has been created successfully !");
         temp.setFont(new Font("Tahoma", Font.BOLD , 13));

         JPanel paneTemp = new JPanel(new GridLayout(3,1));
         paneTemp.add(temp);
         pane.add(paneTemp, BorderLayout.CENTER);

         return pane;
    }
     
    private JPanel createPageEndPane() {
        JPanel pane = new JPanel(new FlowLayout(2));

        backBtn = new JButton("<<Back");
        backBtn.setActionCommand("BackBtn");
        backBtn.addActionListener(this);
        backBtn.setEnabled(false);

        finishBtn = new JButton("Next>>");
        finishBtn.setActionCommand("FinishBtn");
        finishBtn.addActionListener(this);

        cancelBtn = new JButton("Cancel");
        cancelBtn.setActionCommand("CancelBtn");
        cancelBtn.addActionListener(this);

        pane.add(backBtn);
        pane.add(finishBtn);
        pane.add(cancelBtn);

        return pane;
    }
    
    private Container addComponentsToPane() {
        Container pane = frame.getContentPane();
        
        if (!(pane.getLayout() instanceof BorderLayout)) {
            pane.add(new JLabel("Container doesn't use BorderLayout!"));

            return null;
        }

        if (RIGHT_TO_LEFT) {
            pane.setComponentOrientation( java.awt.ComponentOrientation.RIGHT_TO_LEFT);
        }

        pane.add(createCenterPane(), BorderLayout.CENTER);
        pane.add(createPageEndPane(), BorderLayout.PAGE_END);

        return pane;
    }
    
    private void setPermissionDataTable(int index) {
        String per = (String) permissionCombo.getItemAt(index);

        for(int i = 0; i < extTableModel.getRowCount(); i++) {
            extTableModel.setValueAt(per, i, 1);
        }
    }

    private void setPatternCombo(ArrayList<Pattern> arrPattern) {
        patternCombo.removeAllItems();
        for(int i = 0; i < arrPattern.size(); i++) {
            patternCombo.insertItemAt(arrPattern.get(i).getPattern(), i);
        }

        patternCombo.setSelectedIndex(0);
    }

    private void setListExtension(ArrayList<String> ext, String permission) {
        for(int i = 0; i < extTableModel.getRowCount(); i++) {
            extTableModel.setValueAt(ext.get(i), i, 0);
            extTableModel.setValueAt(permission, i, 1);
        }
    }
    
    private void setListExtension(ArrayList<Extension> ext) {
        for(int i = 0; i < extTableModel.getRowCount(); i++) {
            extTableModel.setValueAt(ext.get(i).getExtension(), i, 0);
            
            if(ext.get(i).getPermission() == PermissionExtension.ALLOW) {
                extTableModel.setValueAt(ALLOW, i, 1);
            }
            if(ext.get(i).getPermission() == PermissionExtension.DENY) {
                extTableModel.setValueAt(DENY, i, 1);
            }
        }
    }
    
    private void clearListExtension() {
        for(int i = 0; i < extTableModel.getRowCount(); i++) {
            extTableModel.setValueAt("", i, 0);
            extTableModel.setValueAt("", i, 1);
        }
    }
    
    private void clearListPattern() {
        for(int i = 0; i < patternTableModel.getRowCount(); i++) {
            patternTableModel.setValueAt("", i, 1);
            patternTableModel.setValueAt("", i, 2);
        }
    }
    
    private void deletePattern() {
        int i = patternTable.getSelectedRow();
        if(i>= 0) {
            patternTableModel.setValueAt("", i, 1);
            patternTableModel.setValueAt("", i, 2);
        }
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        try {
            String cmd = e.getActionCommand();
            
            if(cmd.equals("BackBtn")) {
                step--;
                
                if(step == 0) {
                    backBtn.setEnabled(false);
                }
                
                if(step == 1) {
                    if(!projectAddress.getArrayPattern().isEmpty()) {
                        if(projectAddress.getArrayPattern().get(0).getPattern().equals("*/")) {
                            projectAddress.removePatternIndex(0);
                        }
                    }

                    //saveChangeBtn.setEnabled(false);
                }

                finishBtn.setText("Next>>");
                tabbedPane.setSelectedIndex(step);
            }
            else if(cmd.equals("FinishBtn")) {
                step ++;
                backBtn.setEnabled(true);
                
                if(step == 3) {
                    finishBtn.setText("Finished");
                    tabbedPane.setSelectedIndex(step);
                }
                else if(step == 1) {
                    address = addressTxt.getText();
                    
                    if(address == null || address.equals("")) {
                        address = defaultAddress;
                    }
                    
                    if(!address.startsWith("http://") && !address.startsWith("https://")) {
                        address = "http://" + address;
                    }

                    addressAreTxt.setText(address);
                    upLink = Integer.valueOf(levelTxt.getText());

                    projectName = projectNameTxt.getText();
                    
                    String saveTo = outputTxt.getText();
                    tabbedPane.setSelectedIndex(step);
                    
                    if(isNewAddressCreation) {
                        isNewAddressCreation = false;
                        projectAddress = new ProjectAddress(projectName, address, upLink, saveTo);
                    }
                    else {
                        projectAddress.setAddress(address);
                        projectAddress.setUpLink(upLink);
                        projectAddress.setSaveTo(saveTo);
                    }
                }
                else if(step == 2) {
                     tabbedPane.setSelectedIndex(step);
                     ArrayList<Pattern> arrPattern = getPattern();

                     if(isNewPatternCreation) {
                         projectAddress.setArrayPattern(arrPattern);
                         isNewPatternCreation = false;
                     }
                     else {
                         projectAddress.updateArrayPattern(arrPattern);
                     }

                     updatePatternCombo();

                    //clearListExtension();
                }
                else {
                     step = 3;
                     resultDialog = true;
                     frame.setVisible(false);
                }
            }
            else if(cmd.equals("CancelBtn")) {
                dialog.setVisible(false);
                resultDialog = false;
            }
            else if(cmd.equals("allowAllBtn")) {
                setPermissionDataTable(0);
            }
            else if(cmd.equals("choseFileBtn")) {
                JFileChooser fci = new JFileChooser();
                fci.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int returnVal = fci.showOpenDialog(frame);
                
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = fci.getSelectedFile();

                    outputTxt.setText(file.getCanonicalPath());
                }
            }
            else if(cmd.equals("patternCombo")) {
                String patternString = (String)patternCombo.getSelectedItem();
                
                if(patternString == null) {
                    return;
                }

                PermissionPattern permission = null;
                permission = projectAddress.getPermissionPatternOf(patternString);
                
                if(permission == PermissionPattern.ALLOW_ALL ) {
                    allowAllCheckbox.setSelected(true);
                    clearListExtension();
                    stateChange = 0;
                }
                else if(permission == PermissionPattern.DENY_ALL) {
                    denyAllCheckbox.setSelected(true);
                    clearListExtension();
                    stateChange = 0;
                }
                else if (PatternType.indentifyTpe(patternString) == PatternType.LIMIT) {
                    allowAllCheckbox.removeItemListener(this);
                    denyAllCheckbox.removeItemListener(this);

                    allowAllCheckbox.setSelected(false);
                    denyAllCheckbox.setSelected(false);
                    extTable.setEnabled(true);
                    setListExtension(projectAddress.getArrayExtensionsOf(patternString));

                    if(projectAddress.getPermissionPatternOf(patternString) == PermissionPattern.ALLOW_ITEMS)
                    {
                        allowAllCheckbox.setEnabled(true);
                        denyAllCheckbox.setEnabled(false);
                    }

                    if(projectAddress.getPermissionPatternOf(patternString) == PermissionPattern.DENY_ITEMS)
                    {
                        allowAllCheckbox.setEnabled(false);
                        denyAllCheckbox.setEnabled(true);
                    }

                    stateChange = 1;
                    allowAllCheckbox.addItemListener(this);
                    denyAllCheckbox.addItemListener(this);
                }
            }
            else if(cmd.equals("saveChangeBtn")) {
                 if(stateChange % 2 != 0) {
                     saveChangesExtension();
                 }
            }
            else if(cmd.equals("upPatternBtn")) {
                changePriority(true);
            }
            else if(cmd.equals("downPatternBtn"))  {
                changePriority(false);
            }
            else if(cmd.equals("resetBtn")) {
                clearListPattern();
            }
            else if(cmd.equals("deletePatternBtn")) {
                deletePattern();
            }
        }catch(Exception ex) {
            JOptionPane.showMessageDialog(frame, ex.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
        }
    }


    public void itemStateChanged(ItemEvent e) {
        JCheckBox chk = (JCheckBox)e.getSource();
        String name = chk.getName();
        
        if(name.equals("allowAllCheckbox")) {
            if(allowAllCheckbox.isSelected()) {
                denyAllCheckbox.removeItemListener(this);
                extTable.setEnabled(false);
                allowAllCheckbox.setEnabled(true);
                denyAllCheckbox.setSelected(false);
                denyAllCheckbox.setEnabled(false);

                clearListExtension();
                if(stateChange == 1) {
                    String selectedPattern = (String)patternCombo.getSelectedItem();
                    
                    if(selectedPattern.endsWith(Pattern.LIMIT_PATTERN)) {
                        stateChange = 3;
                    }
                    else {
                         stateChange = 0;
                    }
                }
                else if(stateChange == 2) {
                    stateChange = 3;
                }

                denyAllCheckbox.addItemListener(this);
            }
            else {
                String patternString = (String)patternCombo.getSelectedItem();

                if(patternString == null) {
                    return;
                }
                if(patternString.endsWith(Pattern.LIMIT_PATTERN)) {
                    setListExtension(projectAddress.getArrayExtensionsOf(patternString));
                } 
                else {
                    ArrayList<String> ext = projectAddress.getListExtensionsOf(patternString);
                    setListExtension(ext, ALLOW);
                }

                extTable.setEnabled(true);
                stateChange = 1;
            }
        }
        else if(name.equals("denyAllCheckbox")) {
             if(denyAllCheckbox.isSelected() == true) {
                allowAllCheckbox.removeItemListener(this);
                extTable.setEnabled(false);
                allowAllCheckbox.setEnabled(false);
                allowAllCheckbox.setSelected(false);
                denyAllCheckbox.setEnabled(true);
                clearListExtension();

                if(stateChange == 1) {
                    String selectedPattern = (String)patternCombo.getSelectedItem();
                    
                    if(selectedPattern.endsWith(Pattern.LIMIT_PATTERN)) {
                        stateChange = 3;
                    }
                    else {
                        stateChange = 0;
                    }
                }
                else if(stateChange == 2)  {
                    stateChange = 3;
                }
                allowAllCheckbox.addItemListener(this);
            }
            else {
                String patternString = (String)patternCombo.getSelectedItem();
                
                if(patternString == null) {
                    return;
                }
                
                if(patternString.endsWith(Pattern.LIMIT_PATTERN)) {
                    setListExtension(projectAddress.getArrayExtensionsOf(patternString));
                }
                else {
                    ArrayList<String> ext = projectAddress.getListExtensionsOf(patternString);
                    setListExtension(ext, DENY);
                }
                stateChange = 1;
                extTable.setEnabled(true);
            }
        }
    }
    
    private void saveChangesExtension() {
        if(stateChange == 1) {//table change
            ArrayList<Extension> arrExt = getExtension();
            String selectedPattern = (String)patternCombo.getSelectedItem();
            String pad = "";

            if(!selectedPattern.endsWith(Pattern.LIMIT_PATTERN)) {
                pad += Pattern.LIMIT_PATTERN;
            }

            projectAddress.updateArrayExtension(arrExt, selectedPattern + pad);
            if(!selectedPattern.endsWith(Pattern.LIMIT_PATTERN)) {
                updatePatternCombo();
            }
        }
        else if(stateChange == 3) {
            PermissionExtension permission = PermissionExtension.ALLOW;
            if(denyAllCheckbox.isSelected()) {
                permission = PermissionExtension.DENY;
            }

            projectAddress.updateArrayExtension(createArrayExtension(projectAddress.getListExt(), permission), (String)patternCombo.getSelectedItem() + Pattern.LIMIT_PATTERN);
            stateChange = 0;

            updatePatternCombo();
        }
    }
     
    public ArrayList<Extension> createArrayExtension(
            ArrayList<String> arrExt,
            PermissionExtension permission) {
        ArrayList<Extension> res = new ArrayList<Extension>();

        for(int i = 0; i < arrExt.size(); i++) {
            res.add(new Extension(arrExt.get(i),permission ));
        }
        return res;
    }
     
    private void updatePatternCombo() {
        ArrayList<Pattern> list = new ArrayList<Pattern>();
        list = projectAddress.filterPatterns(PermissionPattern.ALLOW_ALL,
                                             PermissionPattern.DENY_ALL);
        list.addAll(projectAddress.filterLimitedPatterns());
        setPatternCombo(list);
    }

    private void changePriority(boolean isUp) {
        int i = patternTable.getSelectedRow();
        
        if((i==0 && isUp) || (i == 39 && !isUp)) {
            return;
        }

        int esp;
        if( isUp) {
            esp = -1;
        }
        else {
            esp = 1;
        }

        if(patternTableModel.getValueAt(i, 1)!= null 
                && patternTableModel.getValueAt(i, 2) != "") {
            System.out.println(String.valueOf(i));
            String pattern = (String) patternTableModel.getValueAt(i, 1);
            String permision = (String) patternTableModel.getValueAt(i, 2);
//            String pattern2 = (String) patternTableModel.getValueAt(i + esp, 1);
//            String permission2 = (String) patternTableModel.getValueAt(i + esp, 2);
            patternTableModel.setValueAt(patternTableModel.getValueAt(i + esp, 1), i, 1);
            patternTableModel.setValueAt(patternTableModel.getValueAt(i + esp, 2), i, 2);
            patternTableModel.setValueAt(pattern, i + esp, 1);
            patternTableModel.setValueAt(permision, i + esp, 2);
        }
    }

    private ArrayList<Pattern> getPattern() {
        ArrayList<Pattern> res = new ArrayList<Pattern>();
        for(int i = 0; i < patternTableModel.getRowCount() ; i++) {
            String pattern = (String)patternTableModel.getValueAt(i, 1);
            String permission = (String)patternTableModel.getValueAt(i, 2);
            
            if(!pattern.equals("") && !permission.equals("")) {
                PermissionPattern pp = PermissionPattern.ALLOW_ITEMS;
                PatternType type = PatternType.indentifyTpe(pattern);
                
                if(permission.equals(ALLOW)) {
                    if(type == PatternType.ITEM) {
                        pp = PermissionPattern.ALLOW_ITEMS;
                    }
                    else if(type == PatternType.ALL) {
                        pp = PermissionPattern.ALLOW_ALL;
                    }
                }
                else if(permission.equals(DENY)) {
                    if(type == PatternType.ITEM) {
                        pp = PermissionPattern.DENY_ITEMS;
                    }
                    else if(type == PatternType.ALL) {
                        pp = PermissionPattern.DENY_ALL;
                    }
                }

                Pattern tmp = new Pattern(pattern, pp);
                tmp.createExtension(projectAddress.getListExt());
                res.add(tmp);
            } else {
                // mặc định insert 40 row vào table, nếu table trống rỗng ->thoát.
                break;
            }
        }
        
        if(res.isEmpty()) {
            Pattern pad = new Pattern("/*", PermissionPattern.ALLOW_ALL);
            pad.createExtension(projectAddress.getListExt());
            res.add(pad);
        }

        return res;
    }
    
    private ArrayList<Extension> getExtension() {
        ArrayList<Extension> res = new ArrayList<Extension>();
        
        for(int i = 0; i < extTableModel.getRowCount(); i++) {
            res.add(new Extension((String)extTableModel.getValueAt(i, 0),
                    extTableModel.getValueAt(i, 1).equals(ALLOW) ? PermissionExtension.ALLOW: PermissionExtension.DENY));
        }

        return res;
    }
    
    public void createAndShowGUI() {
       try {
           UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
       }catch (Exception ec) {
           JOptionPane.showMessageDialog(frame, ec.getMessage());
       }

       //Create and set up the window.
       frame = new JFrame("Create Project Wizard");
       dialog = new JDialog(frame,"Create Project Wizard", true);
       dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
       dialog.setContentPane(addComponentsToPane());
       dialog.setPreferredSize(new Dimension(400, 350));
       dialog.setIconImage(Toolkit.getDefaultToolkit().getImage(WebOffline.imagesPath + "newproject.png"));
       dialog.pack();
       dialog.setResizable(false);
       dialog.setLocation(450, 200);
       dialog.setVisible(true);
       dialog.setLocationRelativeTo(frame);
    }

    public void mouseDragged(MouseEvent e) {
    }

    public void mouseMoved(MouseEvent e) {
        JTextArea tmp = (JTextArea)e.getSource();
        
        if(tmp.getName().equals("addressAreaTxt")) {
            addressAreTxt.setToolTipText(addressAreTxt.getText());
        }
    }

    public void tableChanged(TableModelEvent e) {
//        System.out.println(String.valueOf(e.getFirstRow()));
        if(e.getColumn() == 1) {
            if(patternTableModel.getValueAt(e.getFirstRow(), 2).equals("")
                    || patternTableModel.getValueAt(e.getFirstRow(), 2) == null)
            patternTableModel.setValueAt(ALLOW, e.getFirstRow(), 2);
        }
    }
}

